package com.dyzx.hbb.common.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.dyzx.hbb.common.base.PageQuery;
import com.dyzx.hbb.common.base.PageResult;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.constant.InitConfig;
import com.dyzx.hbb.modules.sys.entity.SysWork;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Map;

/**
 * 自定义基础控制器
 * 
 * 功能说明：提供自定义查询功能的基础控制器实现，扩展自BaseCustomListController
 * 主要职责：
 * - 定义获取基础服务的抽象方法
 * - 定义构建查询条件的抽象方法
 * - 实现根据ID查询详情的功能
 * - 处理实体字段的自动填充
 * 
 * 设计意图：
 * 为需要自定义查询逻辑的控制器提供基础实现，支持灵活的查询条件构建
 * 
 * @param <S> 服务类型，必须是 IService 的子类
 * @param <T> 实体类型
 * @param <Q> 查询参数类型
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
public abstract class BaseCustomController<S extends IService<T>, T, Q> extends BaseCustomListController<S, T, Q> {
    private static final String ORGAN_FIELD = "organId";
    private static final String OPRERATOR_FIELD = "operatorId";
    private static final String CREATE_DATE_FIELD = "createDate";
    private static final String UPDATE_DATE_FIELD = "updateDate";
    private static final String STATUS_FIELD = "status";

    private final Class<T> entityClass;

    @SuppressWarnings("unchecked")
    protected BaseCustomController() {
        this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    /**
     * 获取服务
     */
    protected abstract S getBaseService();


    /**
     * 构建查询条件
     */
    protected abstract   MyLambdaQueryWrapper<T> queryInfoWrapper();




    @Operation(summary = "根据ID查询")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(@PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<T> objectQueryWrapper = queryInfoWrapper();
        if (objectQueryWrapper==null){
            objectQueryWrapper = new MyLambdaQueryWrapper<>();
        }
        T entity = createEntity();
        Class<?> aClass = entity.getClass();
        // 方案二：检查字段存在性（需要时使用）
        boolean hasOrganField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> ORGAN_FIELD.equals(f.getName()));
        if(hasOrganField){
            //objectQueryWrapper.apply("organ_id = {0}", organId);
         /*   if(SecurityContextHolder.isNotAdmin()) {
                objectQueryWrapper.apply("organ_id = {0}", organId);
            }*/
         //   objectQueryWrapper.and(wrapper -> wrapper.apply("organ_id = {0}", organId).or().apply("organ_id IS NULL"));
            objectQueryWrapper.apply(" (organ_id = {0} or organ_id IS NULL)", organId);
            objectQueryWrapper.orgNameSql("organ_id").as("organ_name");
        }
        boolean hasOperatorField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> OPRERATOR_FIELD.equals(f.getName()));
        if(hasOperatorField) {
            System.out.println("hasOperatorField:"+hasOperatorField);
            objectQueryWrapper.userNameSql("operator_id").as("operator_name");
            objectQueryWrapper.select("operator_id");
        }
        boolean hasCreateDateField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> CREATE_DATE_FIELD.equals(f.getName()));
        if(hasCreateDateField) {
            System.out.println("hasCreateDateField:"+hasCreateDateField);
            objectQueryWrapper.select("create_date");
        }
        boolean hasUpdateDateField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> UPDATE_DATE_FIELD.equals(f.getName()));
        if(hasUpdateDateField) {
            System.out.println("hasUpdateDateField:"+hasUpdateDateField);
            objectQueryWrapper.select("create_date");
        }
        boolean hasStatusField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> STATUS_FIELD.equals(f.getName()));
        if(hasStatusField) {
            System.out.println("hasStatusField:"+hasStatusField);
            objectQueryWrapper.select("status");
        }

        Map<String, Object> map = getBaseService().getMap(objectQueryWrapper.apply("id={0}", id).last("limit 1"));
        if(map == null){
            return Result.error(404,"数据不存在");
        }
        return Result.ok(map);
    }
    private T createEntity() {
        T entityCopy;
        try {
            entityCopy = entityClass.getDeclaredConstructor().newInstance();

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return entityCopy;
    }

}
